package com.ui.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wanmei.util.JsonMsg;
import com.wanmei.commons.JsonUtils;
import com.wanmei.pojo.CartItem;
import com.wanmei.pojo.Product;
import com.wanmei.pojo.Productkuid;
import com.ui.service.ProductService;
import com.ui.service.ProductKuidService;

@Controller
public class WebUiProductCookieController {
    @Autowired
    ProductService productService;
    @Autowired
    private ProductKuidService productKuidService;
    private static final String CART_ITEM = "CART_ITEM";

    @RequestMapping("/cartview")
    public String cartview() {
        return "shoppingcart";
    }

    @RequestMapping("/getcartview")
    public String getCartListView(HttpServletRequest request) {
        //数据从cookie中读取
        List<CartItem> list = getCookieList(request);
        request.setAttribute("cart", list);
        return "shoppingcart";
    }

    //添加购物车
    @RequestMapping("/addCart")
    @ResponseBody
    public Object addCartProudct(@RequestParam("pid") Integer pid, @RequestParam("num") Integer num,
                                 @RequestParam("kuid") Integer kuid, HttpServletRequest request, HttpServletResponse response) {
        CartItem cartItem = new CartItem();//创建购物车对象
        // 获取商品ID
        cartItem.setId(pid);
        // 获取购买数量
        cartItem.setNum(num);
        // 获取KUID
        cartItem.setKuid(kuid);

        //通过pid获取到product对象
        Product product = productService.selectByPrimaryKey(pid);
        //通过kuid获取productKuid对象
        Productkuid productKuid= productKuidService.getByPrimaryKey(kuid);
        cartItem.setProduct(product);
        cartItem.setProductKuid(productKuid);


        // 1、取Cookie购物车里的列表
        List<CartItem> list = getCookieList(request);
        // 1-1、判断是否存在购物车
        if(list==null)
            list = new ArrayList<>();// 如果购物车为空创建list
        boolean state=false;
        for(CartItem item : list) {
            // 如果存在购物车，并存在商品修改商品数量
            if(cartItem.getKuid()==item.getKuid()&&cartItem.getId()==item.getId()) {
                item.setNum(item.getNum()+cartItem.getNum());
                state=true;
                break;
            }
        }
        if(!state) {
            list.add(cartItem);// 如果商品不存在购物车，将商品添加到购物车
        }

        // 将list转化成json串保存到cookie中
        boolean result= addCookies(list,response);
        // 返回操作状态
        JsonMsg msg = new JsonMsg();
        if(result) {
            msg.setCode(200);
            msg.setMsg("购物车添加成功");
        }else {
            msg.setCode(500);
            msg.setMsg("购物车添加失败");
        }
        return msg;
    }

    // 从cookie中获取购物信息
    public List<CartItem> getCookieList(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        List<CartItem> list=null;
        if(cookies==null)
            return list;
        for(Cookie c:cookies) {
            if(CART_ITEM.equals(c.getName())) {
                String value = c.getValue();
                //解码
                String valueDecoder=null;
                try {
                    valueDecoder = URLDecoder.decode(value, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                list = JsonUtils.jsonToList(valueDecoder, CartItem.class);
                break;
            }
        }
        System.out.println("购物车里面的内容为+"+list);
        return list;
    }

    public boolean addCookies(List<CartItem> items,HttpServletResponse response) {
        boolean state = true;
        //先编码
        String itemsList = JsonUtils.objectToJson(items);
        String encode=null;
        try {
            //urlDecoder = URLDecoder.decode(itemsList, "UTF-8");
            encode = URLEncoder.encode(itemsList, "UTF-8");
            Cookie cookie = new Cookie(CART_ITEM, encode);
            cookie.setMaxAge(24*3600);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            state=false;
        }
        return state;
    }

    @RequestMapping("/deleteCar")
    public String deleteCar(HttpServletRequest request,HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            String cookieName = cookies[i].getName();
            if (StringUtils.isNotBlank(cookieName) && (cookieName.equals("CART_ITEM"))) {
                Cookie cookie = new Cookie(cookies[i].getName(), "");
                cookie.setMaxAge(0);
                cookie.setPath(request.getContextPath());
                cookie.setDomain(request.getServerName());
                response.addCookie(cookie);
            }
        }
        return "shoppingcart";
    }


}
